package com.yanqu.road.server.manager.activity.langyamemorial;

import com.yanqu.road.dao.impl.activity.langyamemorial.CrossLangYaMemorialAllDataDaoImpl;
import com.yanqu.road.dao.impl.activity.langyamemorial.CrossLangYaMemorialBuildDataDaoImpl;
import com.yanqu.road.dao.impl.activity.langyamemorial.CrossLangYaMemorialNoticeDataDaoImpl;
import com.yanqu.road.dao.impl.activity.langyamemorial.CrossLangYaMemorialUserDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.langyamemorial.CrossLangYaMemorialAllData;
import com.yanqu.road.entity.activity.langyamemorial.CrossLangYaMemorialBuildData;
import com.yanqu.road.entity.activity.langyamemorial.CrossLangYaMemorialNoticeData;
import com.yanqu.road.entity.activity.langyamemorial.CrossLangYaMemorialUserData;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.LangYaMemorialProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class LangYaMemorialActivity {

    private ActivityInfo activityInfo;

    //玩家贡献进度
    Map<Long, CrossLangYaMemorialUserData> userProcessDataMap;

    //全服进度
    CrossLangYaMemorialAllData activityData;

    //活动配置项
    Map<String, ActivityConfig> activityConfigMap;

    //建阁层数
    private List<CrossLangYaMemorialBuildData> buildDataList;

    //公告
    private List<CrossLangYaMemorialNoticeData> noticeDataList;

    private int noticeCount;

    private int atticView;

    public LangYaMemorialActivity(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public void init(){
        List<Integer> activityIdList = new ArrayList<>();
        activityIdList.add(activityInfo.getActivityId());
        activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(activityInfo.getActivityId());

        noticeCount = activityConfigMap.get(eActivityConfigType.LANGYA_ATTIC_NOTICE.getName()).getIntValue();

        atticView = activityConfigMap.get(eActivityConfigType.LANGYA_ATTIC_VIEW.getName()).getIntValue();

        //数据加载
        activityData = new CrossLangYaMemorialAllDataDaoImpl().getCrossLangYaMemorialAllData(activityInfo.getActivityId());
        if(activityData == null){
            activityData = new CrossLangYaMemorialAllData();
            activityData.setActivityId(activityInfo.getActivityId());
            activityData.setInsertOption();
        }
        //玩家进度贡献
        userProcessDataMap = new CrossLangYaMemorialUserDataDaoImpl().getCrossLangYaMemorialUserData(activityInfo.getActivityId());

        //建阁记录
        buildDataList = new CrossLangYaMemorialBuildDataDaoImpl().getCrossLangYaMemorialBuildData(activityInfo.getActivityId());
        Collections.reverse(buildDataList);

        //公告
        noticeDataList = new CrossLangYaMemorialNoticeDataDaoImpl().getCrossLangYaMemorialNoticeData(activityInfo.getActivityId(), noticeCount);
        Collections.reverse(noticeDataList);
    }

    public void save(){

        if(activityData.isInsertOption()){
            new CrossLangYaMemorialAllDataDaoImpl().add(activityData);
        }else if(activityData.isUpdateOption()){
            new CrossLangYaMemorialAllDataDaoImpl().update(activityData);
        }

        for (Map.Entry<Long, CrossLangYaMemorialUserData> dataEntry : userProcessDataMap.entrySet()) {
            CrossLangYaMemorialUserData data = dataEntry.getValue();
            if(data.isInsertOption()){
                new CrossLangYaMemorialUserDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new CrossLangYaMemorialUserDataDaoImpl().update(data);
            }
        }

        for (int i = 0; i < buildDataList.size(); i++) {
            CrossLangYaMemorialBuildData data = buildDataList.get(i);
            if(data.isInsertOption()){
                new CrossLangYaMemorialBuildDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new CrossLangYaMemorialBuildDataDaoImpl().update(data);
            }
        }

        for (int i = 0; i < noticeDataList.size(); i++) {
            CrossLangYaMemorialNoticeData data = noticeDataList.get(i);
            if(data.isInsertOption()){
                new CrossLangYaMemorialNoticeDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new CrossLangYaMemorialNoticeDataDaoImpl().update(data);
            }
        }

    }

    public synchronized void calCrossLionDanceAllData() {
        if(activityData == null || userProcessDataMap == null){
            return;
        }
        if(userProcessDataMap.size() == 0){
            return;
        }
        long count = 0;
        for (Map.Entry<Long, CrossLangYaMemorialUserData> entry : userProcessDataMap.entrySet()) {
            count += entry.getValue().getBuildValue();
        }

        if(count != activityData.getBuildValue()){
            activityData.setBuildValue(count);
            activityData.setUpdateTime(System.currentTimeMillis());
            //同步给活动所有区服
            if(activityInfo != null){
                LangYaMemorialProto.CrossLangYaMemorialSyncAllBuildValueMsg.Builder sync = LangYaMemorialProto.CrossLangYaMemorialSyncAllBuildValueMsg.newBuilder();
                sync.setActivityId(activityInfo.getActivityId());
                sync.setBuildValue(activityData.getBuildValue());
                for (Long sid : activityInfo.getServerIdList()) {
                    MessageHelper.sendPacket(sid, 0, YanQuMessageUtils.buildMessage(Protocol.S_LANGYA_MEMORIAL_ALL_CONTRIBUTION_SYNC_FROM_CROSS, sync));
                }
            }
        }
    }

    public void updateUserValue(long userId, long process, boolean needSync){
        synchronized (CrossLangYaMemorialMgr.getUserLocker(userId)){
            CrossLangYaMemorialUserData userProcessData = userProcessDataMap.get(userId);
            if(userProcessData == null){
                userProcessData = new CrossLangYaMemorialUserData();
                userProcessData.setInsertOption();
                userProcessData.setActivityId(activityInfo.getActivityId());
                userProcessData.setUserId(userId);
            }
            userProcessData.setBuildValue(process);
            userProcessData.setUpdateTime(System.currentTimeMillis());
            if(userProcessData.isInsertOption()){
                userProcessDataMap.put(userId, userProcessData);
            }
            CrossLangYaMemorialMgr.getLogger().info("-------------- 玩家进度 {}：{}", userProcessData.getUserId(), userProcessData.getBuildValue());
        }
        if(needSync){
            calCrossLionDanceAllData();
        }
    }

    //建阁
    public void preBuild(long serverId, long userId, String consume, int commonTimes, List<Integer> typeList, long buildValue){

        //返回跨服结算
        LangYaMemorialProto.CrossLangYaMemorialBuildRespMsg.Builder builder = LangYaMemorialProto.CrossLangYaMemorialBuildRespMsg.newBuilder();
        synchronized (activityData){

            long no = activityData.getBuildTimes();
            for (int type : typeList) {
                CrossLangYaMemorialBuildData data = new CrossLangYaMemorialBuildData();
                data.setActivityId(activityInfo.getActivityId());
                data.setBuildType(type);
                data.setBuildNo(++no);
                data.setInsertOption();
                data.setUserId(userId);
                buildDataList.add(data);
            }
            activityData.setBuildTimes(no);

            if(buildDataList.size() > 10000){
                buildDataList.remove(0);
            }

            int num = 0;
            for (int i = buildDataList.size() - 1; i >= 0 && num < atticView; i--) {
                CrossLangYaMemorialBuildData data = buildDataList.get(i);
                LangYaMemorialProto.LangYaMemorialAtticData.Builder buildData = LangYaMemorialProto.LangYaMemorialAtticData.newBuilder();
                buildData.setNo(data.getBuildNo());
                buildData.setUserId(data.getUserId());
                buildData.setType(data.getBuildType());
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(data.getUserId());
                if(userBaseInfo != null) {
                    buildData.setBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }else {
                    continue;
                }
                builder.addList(buildData);
                num++;
            }
        }

        updateUserValue(userId, buildValue, false);

        //返回跨服结算
//        LangYaMemorialProto.CrossLangYaMemorialBuildRespMsg.Builder builder = LangYaMemorialProto.CrossLangYaMemorialBuildRespMsg.newBuilder();
        builder.setRet(0);
        builder.setConsume(consume);
        builder.setCommonTimes(commonTimes);
        builder.addAllType(typeList);
        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.S_LANGYA_MEMORIAL_BUILD_FROM_CROSS, builder));
    }

    public void addDrawNotice(long serverId, long playerId, List<LangYaMemorialProto.LangYaMemorialNoticeMsg> noticeList) {
        synchronized (noticeDataList){
            for (LangYaMemorialProto.LangYaMemorialNoticeMsg noticeMsg : noticeList) {
                CrossLangYaMemorialNoticeData noticeData = new CrossLangYaMemorialNoticeData();
                noticeData.setActivityId(activityInfo.getActivityId());
                noticeData.setGetTime(noticeMsg.getTime());
                noticeData.setServerId(serverId);
                noticeData.setUserId(playerId);
                noticeData.setNickName(noticeMsg.getNickName());
                noticeData.setReward(noticeMsg.getReward());
                noticeData.setParam("");
                noticeData.setInsertOption();
                noticeDataList.add(noticeData);
            }
            while (noticeDataList.size() > noticeCount){
                noticeDataList.remove(0);
            }
        }
    }

    public LangYaMemorialProto.LangYaMemorialNoticeRespMsg.Builder getNoticeList() {

        LangYaMemorialProto.LangYaMemorialNoticeRespMsg.Builder respMsg = LangYaMemorialProto.LangYaMemorialNoticeRespMsg.newBuilder();

        List<CrossLangYaMemorialNoticeData> list = noticeDataList;
        if(list != null){
            for (int i = 0; i < list.size(); i++) {
                LangYaMemorialProto.LangYaMemorialNoticeMsg.Builder builder = LangYaMemorialProto.LangYaMemorialNoticeMsg.newBuilder();
                CrossLangYaMemorialNoticeData noticeData = list.get(i);
                builder.setTime(noticeData.getGetTime());
                builder.setReward(noticeData.getReward());
                builder.setServerId(noticeData.getServerId());
                builder.setNickName(noticeData.getNickName());
                builder.setType(0);
                respMsg.addNotice(builder);
            }
        }
        respMsg.setRet(0);
        return respMsg;
    }

    /**
     * 建阁子列表
     */
    public void getAtticList(long serverId, long playerId, int page, int pageSize) {

        LangYaMemorialProto.LangYaMemorialAtticListRespMsg.Builder respMsg = LangYaMemorialProto.LangYaMemorialAtticListRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setPageSize(pageSize);
        respMsg.setPage(page);


        List<CrossLangYaMemorialBuildData> list = new ArrayList<>(buildDataList);
        int size = list.size();
        int end = size - (page - 1) * pageSize;
        for (int i = end - 1; i >= 0 && i >= end - pageSize; i--) {
            CrossLangYaMemorialBuildData data = list.get(i);
            LangYaMemorialProto.LangYaMemorialAtticData.Builder builder = LangYaMemorialProto.LangYaMemorialAtticData.newBuilder();
            builder.setUserId(data.getUserId());
            builder.setNo(data.getBuildNo());
            builder.setType(data.getBuildType());
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(data.getUserId());
            if(userBaseInfo != null){
                builder.setBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            }
            respMsg.addAttic(builder);
        }

        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_LANGYA_MEMORIAL_ATTIC_GET, respMsg));
    }

    public void syncAllBuildProcess(long serverId) {
        LangYaMemorialProto.CrossLangYaMemorialSyncAllBuildValueMsg.Builder sync = LangYaMemorialProto.CrossLangYaMemorialSyncAllBuildValueMsg.newBuilder();
        sync.setActivityId(activityInfo.getActivityId());
        sync.setBuildValue(activityData.getBuildValue());
        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_LANGYA_MEMORIAL_ALL_CONTRIBUTION_SYNC_FROM_CROSS, sync));
    }
}
